from django.shortcuts import render
from django.http import JsonResponse
from django.contrib.contenttypes.models import ContentType
from django.core import exceptions

from .models import LikeNum, LikeRecord

def success_response(liked_num):
    data = {}
    data['status'] = 'SUCCESS'
    data['liked_num'] = liked_num
    return JsonResponse(data)

def error_response(message, code):
    '''
    400表示未登录
    401表示用户未点赞，无法取消
    402表示对象未被点赞，无法取消
    403表示用户已点赞，无法重复点赞
    404表示评论对象不存在
    '''
    data = {}
    data['status'] = 'ERROR'
    data['message'] = message
    data['code'] = code
    return JsonResponse(data)

def press_like(request):
    user = request.user
    pressed = (request.GET.get('pressed') == 'true')
    # 获取数据，判断评论对象是否存在
    try:
        content_type = ContentType.objects.get(model=request.GET.get('content_type'))
        object_id = int(request.GET.get('object_id'))
        obj = content_type.get_object_for_this_type(pk=object_id)
    except exceptions.ObjectDoesNotExist:
        return error_response('评论对象不存在', 404)

    if not user.is_authenticated:
        return error_response('目前用户未登录', 400)

    if pressed:
        # 按下点赞的状态再次按下，因此我们需要递减点赞数
        if LikeNum.objects.filter(content_type=content_type, object_id=object_id).exists():
            # 获取对应的用户点赞记录
            like_record, created = LikeRecord.objects.get_or_create(content_type=content_type,
                                                                    object_id=object_id, user=user)
            if not created:
                # 对应用户点赞记录存在，点赞数-1
                like_count = LikeNum.objects.get(content_type=content_type, object_id=object_id)
                like_count.liked_num -= 1
                like_count.save()
                # 删除记录
                like_record.delete()
                return success_response(like_count.liked_num)
            else:
                # 按下了点赞，没有对应的用户记录，错误
                return error_response('用户未曾点赞，无法取消点赞', 401)
        else:
            # 出错，没有对应的点赞数不应该是按下点赞的状态
            return error_response('该对象未被点赞过，无法取消点赞', 402)
    else:
        # 没有按下点赞的状态，按下点赞，因此我们需要递增点赞数
        like_record, created = LikeRecord.objects.get_or_create(content_type=content_type,
                                                                object_id=object_id, user=user)
        if created:
            # 保存点赞记录
            like_record.save()
            # 点赞总数 + 1
            like_count, create = LikeNum.objects.get_or_create(content_type=content_type, object_id=object_id)
            like_count.liked_num += 1
            like_count.save()
            return success_response(like_count.liked_num)
        else:
            # 用户已经点过赞了
            return error_response('用户已经点赞过，无法重复点赞', 403)